/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-20 11:28:37
 * @Description  : 一些通用函数
 */

const { Role, Permission } = require('@/models/model')
const { genSalt, MD5 } = require('./md5')

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 判断两个数组是否相等
 * @param {*} array1 数组1
 * @param {*} array2 数组2
 * @returns {boolean}
 */
module.exports.arraysIsEqual = (array1, array2) => {
  if (array1.length !== array2.length) {
    return false
  }
  for (let i = 0; i < array1.length; i++) {
    if (array1[i] !== array2[i]) {
      return false
    }
  }
  return true
}

/**
 * 根据原始密码，获取新的密码和盐值
 * @param {*} password 原始密码
 * @returns {object} 盐值和新的密码
 */
module.exports.getNewPwd = async (password) => {
  const salt = genSalt()
  const newPwd = await MD5(password, salt)
  return {
    salt,
    newPwd
  }
}

/**
 * 检验角色的大小关系
 */
module.exports.compareRole = async (roleA, roleB) => {
  let a = await Role.findByPk(BigInt(roleA), {
    include: [
      {
        model: Permission,
        attributes: ['id']
      }
    ]
  })

  a = a.Permissions.map((item) => item.id)

  let b = await Role.findByPk(BigInt(roleB), {
    include: [
      {
        model: Permission,
        attributes: ['id']
      }
    ]
  })

  b = b.Permissions.map((item) => item.id)

  const res = a.every((item) => {
    return b.includes(item)
  })

  // true代表，a小于b

  return res
}
